<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 15-6-23
 * Time: 下午3:27
 * @author 郑钟良<zzl@ourstu.com>
 */

namespace Addons\Consult\Controller;


use Think\Controller;

class ConsultController extends Controller{
    protected $consultModel;
    protected $consultCategoryModel;

    public function _initialize()
    {
        $this->consultModel=D('Addons://Consult/Consult');
        $this->consultCategoryModel=D('Addons://Consult/ConsultCategory');
    }

    public function consult()
    {
        $aLimit=I('post.limit',20,'intval');
        $map['table_name']=I('post.table_name','','text');
        $map['row_id']=I('post.row_id',0,'intval');
        $aType_id=I('post.type_id',0,'intval');
        $map['status']=1;
        if($aType_id!=0){
            $map['type_id']=$aType_id;
            $type_info=$this->consultCategoryModel->getData($aType_id);
            if($type_info['tip']!=''){
                $res['tip']=$type_info['tip'];
            }else{
                $res['tip']=$this->_getAddonsConfig('tip');
            }
        }else{
            $res['tip']=$this->_getAddonsConfig('tip');
        }

        //搜索 start
        $keyword=I('post.consult_keyword','','text');
        if($keyword!=''){
            $map['content|answer']=array('like','%'.$keyword.'%');
        }
        //搜索 end

        list($list,$totalCount)=$this->consultModel->getList($map,'create_time desc',$aLimit);
        $this->assign('consult_list',$list);
        $this->assign('consult_totalCount',$totalCount);
        if($totalCount>$aLimit){
            $this->assign('show_more',1);
        }
        $res['html']=$this->fetch(T('Addons://Consult@Consult/consult_list'));
        $this->ajaxReturn($res);
    }

    public function consultMore()
    {
        $aConsultPage=I('post.page',2,'intval');
        $aLimit=I('post.limit',20,'intval');
        $map['table_name']=I('post.table_name','','text');
        $map['row_id']=I('post.row_id',0,'intval');
        $aType_id=I('post.type_id',0,'intval');
        $map['status']=1;
        if($aType_id!=0){
            $map['type_id']=$aType_id;
            $type_info=$this->consultCategoryModel->getData($aType_id);
            if($type_info['tip']!=''){
                $res['tip']=$type_info['tip'];
            }else{
                $res['tip']=$this->_getAddonsConfig('tip');
            }
        }

        //搜索 start
        $keyword=I('post.consult_keyword','','text');
        if($keyword!=''){
            $map['content|answer']=array('like','%'.$keyword.'%');
        }
        //搜索 end

        list($list,$totalCount)=$this->consultModel->getList($map,'create_time desc',$aLimit,$aConsultPage);
        $this->assign('consult_list',$list);

        $res['html']=$this->fetch(T('Addons://Consult@Consult/consult_list_more'));
        $res['show_num']=($aConsultPage-1)*$aLimit+count($list);
        if($totalCount>$res['show_num']){
            $res['show_more']=1;
        }
        $this->ajaxReturn($res);
    }

    public function delete()
    {
        $data['id']=I('post.consult_id',0,'intval');
        $consult=$this->consultModel->getData($data['id']);
        $this->checkAuth('Addons/Consult/Consult/delete',$consult['goods_uid'],'你没有权限删除该咨询！');
        $data['status']=-1;
        $res=$this->consultModel->editData($data);
        if($res){
            action_log('consult_delete','Consult',$data['id'],get_uid());
            $result['status']=1;
        }else{
            $result['status']=0;
            $result['info']='操作失败！'.$this->consultModel->getError();
        }
        $this->ajaxReturn($result);
    }

    public function ask()
    {
        $this->checkAuth('Addons/Consult/Consult/ask',-1,'你没有权限发表咨询！');
        $data['table_name']=I('table_name','','text');
        if(IS_POST){
            $this->checkActionLimit('consult_ask','Consult',null,get_uid());
            $data['row_id']=I('post.row_id',0,'intval');
            $data['type_id']=I('post.type_id',0,'intval');
            $data['content']=I('post.content','','text');
            $data['goods_uid']=I('post.goods_uid',0,'intval');
            $data['from_url']=I('post.from_url','','text');
            if(mb_strlen($data['content'],'utf-8')<5){
                $this->error('咨询内容不能小于5个字！');
            }
            $data['uid']=get_uid();
            $data['status']=1;
            $data['create_time']=time();
            $res=$this->consultModel->editData($data);
            if($res){
                action_log('consult_ask','Consult',$res,get_uid());
                $result['status']=1;
                $result['info']='发表咨询成功！请耐心等待回复~';

                $title = get_nickname(get_uid())." 发表咨询";
                $message = '咨询内容：' . $data['content'];
                D('Common/Message')->sendMessage($data['goods_uid'], $title, $message,$data['from_url'], null, get_uid(),1);
            }else{
                $result['status']=0;
                $result['info']='发表咨询失败！'.$this->consultModel->getError();
            }
            $this->ajaxReturn($result);
        }else{
            $this->_assignCategory($data);
            $this->display(T('Addons://Consult@Consult/ask'));
        }
    }

    public function answer()
    {
        $aId=I('consult_id',0,'intval');
        $consult=$this->consultModel->getData($aId);
        $this->checkAuth('Addons/Consult/Consult/answer',$consult['goods_uid'],'你没有权限回复该咨询！');
        if(IS_POST){
            $data['id']=$aId;
            $data['answer']=I('post.answer','','text');
            if(mb_strlen($data['answer'],'utf-8')<=0){
                $this->error('回复咨询内容不能为空！');
            }
            $data['update_time']=time();
            $res=$this->consultModel->editData($data);
            if($res){
                action_log('consult_answer','Consult',$aId,get_uid());
                $result['status']=1;
                $result['info']='回复咨询成功！';

                if(mb_strlen($consult['answer'],'utf-8')>0){
                    $title = get_nickname(get_uid())." 更新了对你的咨询的回复";
                    $message = '咨询内容：' . $consult['content'].'<br/>更新后回复内容：'.$data['answer'];
                }else{
                    $title = get_nickname(get_uid())." 回复你的咨询";
                    $message = '咨询内容：' . $consult['content'].'<br/>回复内容：'.$data['answer'];
                }
                D('Common/Message')->sendMessage($consult['uid'], $title, $message, $consult['from_url'], null, get_uid(),1);
            }else{
                $result['status']=0;
                $result['info']='回复咨询失败！'.$this->consultModel->getError();
            }
            $this->ajaxReturn($result);
        }else{
            $this->assign('consult',$consult);
            $this->display(T('Addons://Consult@Consult/answer'));
        }
    }

    private function _getAddonsConfig($name='')
    {
        $config=S('CONSULT_ADDONS_CONFIG');
        if(!$config){
            $map['name']    =   "Consult";
            $map['status']  =   1;
            $config  =   M('Addons')->where($map)->getField('config');
            $config=json_decode($config,true);

            $use_space = str_replace("\r", '', $config['use_space']);
            $use_space = explode("\n", $use_space);
            $config['use_space']=array();
            foreach ($use_space as &$v) {
                $temp = explode(':', $v);
                $config['use_space'][$temp[0]] = $temp[1];
            }

            S('CONSULT_ADDONS_CONFIG',$config);
        }
        if($name!=''){
            return $config[$name];
        }
        return $config;
    }

    private function _assignCategory($data)
    {
        $map_category['use_space']=array('like',array('%['.$data['table_name'].']%',''));
        $map_category['status']=1;
        $list=D('Addons://Consult/ConsultCategory')->getList($map_category);
        $this->assign('consult_category_list',$list);
    }
} 